package nl.hanze.web.t41.http;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class HTTPHeader {

	private String header; // the header

	public HTTPHeader(int return_code, int file_type, File file) {

		header = construct_http_header(return_code, file_type, file);
	}

	/*
	 * create the http header
	 */
	private String construct_http_header(int return_code, int file_type,
			File file) {
		String s = "HTTP/1.0 ";
		switch (return_code) {
		case 200:
			s = s + "200 OK";
			break;
		case 400:
			s = s + "400 Bad Request";
			break;
		case 401:
			s = s + "401 Unauthorized";
			break;
		case 403:
			s = s + "403 Forbidden";
			break;
		case 404:
			s = s + "404 Not Found";
			break;
		case 500:
			s = s + "500 Internal Server Error";
			break;
		case 501:
			s = s + "501 Not Implemented";
			break;
		}

		s = s + "\r\n";
		s = s + "Connection: close\r\n";
		s = s + "Server: ferman HTTP v0.1\r\n"; // server name
		
		if (return_code == 401)
			s = s + "WWW-Authenticate: Basic realm=\"Secure Area\"\r\n";

		// the content type
		switch (file_type) {
		case 0:
			s = s + "Content-Type: text/html\r\n";
			break;
		case 1:
			s = s + "Content-Type: image/jpeg\r\n";
			break;
		case 2:
			s = s + "Content-Type: image/jpg\r\n";
			break;
		case 3:
			s = s + "Content-Type: image/gif\r\n";
			break;
		case 4:
			s = s + "Content-Type: image/png\r\n";
			break;
		default:
			s = s + "Content-Type: text/html\r\n";
			break;
		}

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int b;
		try {
			InputStream fin = new FileInputStream(file);
			while ((b = fin.read()) != -1) { // write to ByteArrayOutputStream
				baos.write(b);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		s = s + "Content-Length: " + baos.size() + "\r\n";
		s = s + "\r\n"; // end of the httpheader

		return s;
	}

	public String getHeader() {
		return header;
	}
}